<template>
    <div class="container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span>重置密码</span>
                </div>
            </template>
            <el-row>
                <el-col :span="12">
                    <el-form :model="userPassword" :rules="rules" label-width="100px" size="large">
                        <el-form-item label="原密码" prop="old_pwd">
                            <el-input v-model="userPassword.old_pwd"></el-input>
                        </el-form-item>
                        <el-form-item label="新密码" prop="new_pwd">
                            <el-input v-model="userPassword.new_pwd" minlength="5" maxlength="15"></el-input>
                        </el-form-item>
                        <el-form-item label="确认新密码" prop="re_pwd">
                            <el-input v-model="userPassword.re_pwd" minlength="5" maxlength="15"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="updatePassword">提交修改</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserInfoStore } from '@/stores/userInfo.js'
import { useTokenStore } from '@/stores/token'
import { userPasswordUpdateService, userAvatarUpdateService } from '@/api/user.js'
import { ElMessage } from 'element-plus'

const userInfoStore = useUserInfoStore();
const tokenStore = useTokenStore()

const userPassword = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})

const checkRePwd = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== userPassword.value.new_pwd) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

const rules = {
    old_pwd: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5-16位非空字符', trigger: 'blur' }
    ],
    re_pwd: [
        { required: true, validator: checkRePwd, trigger: 'blur' },

    ]
}

const updatePassword = async () => {
    let result = await userPasswordUpdateService(userPassword.value);
    ElMessage.success('修改成功');
    tokenStore.removeToken()
}

</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    display: flex;
    justify-content: center;

    .page-container {
        width: 95%;
        margin-top: 20px;
    }
}
</style>